const path = require("path")
const genImports = (cmds,ph)=>{
	return cmds.map((cmd)=>{
		return `import ${cmd.key} from '${path.join(ph,cmd.path)}'`
	}).join(" \n")
}
const genTplStr = (input)=>{
	let tplArr = []
	for(let fn in input){
		if(typeof input[fn]==="function")
			tplArr.push(input[fn].toString())
	}
	return tplArr.join("\n")
}
const hasTool = (cmds)=>{
	return cmds.filter(cmd=>cmd.key==="Tool")
}
module.exports = function(source,a,b,c){
	const MngTemplate = require('./action-template')

	let rsource 	= "return "+source
	let os 			= new Function(rsource)()
	let importCommand = os.importCommand||[]
	if(os.tool)
		importCommand.push({
			key:"Tool",
			path:os.tool
		});
	let name 		= os.name
	let _extends 	= os._extends||{key:"Mng",path:"./paint_tool/mng"} 
	let ph 			= path.resolve(__dirname,'../script')
	let importStr	= genImports(importCommand,ph)
	let Tool 		= hasTool(importCommand)[0]
	let toolStr 	= Tool?"this.tool = new Tool()\n":""

	delete os.importCommand
	delete os._extends
	let mngStr 		= JSON.stringify(os)
	let mngFnStr 	= genTplStr(os)
	let templateStr = genTplStr(MngTemplate)
	let code = `
		import Algo from '${path.join(ph,"./algo")}'
		import Utils from '${path.join(ph,"./utils")}'
		import ${_extends.key} from '${path.join(ph,_extends.path)}'
		import {Cst,Action,EN} from '${path.join(ph,"./config")}'
		${importStr}
		export default class ${os.name} extends ${_extends.key}{
			constructor(...args){
				super(...args)
				this.__config = ${mngStr}
				this.merge(this.__config)
				delete this.__config
				${toolStr}
				this.emit(Cst.init)
			}
			${templateStr}
			${mngFnStr}
		}
	`
	// console.log(mngStr,mngFnStr,templateStr)
	// if(name==="RectMng"||name==="AbstractMng")
	// console.log(code)
	return code
}
	